<?php

namespace common\models\user;

use Yii;

/**
 * 用户积分账户日志信息
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class UserAccountLog extends \common\models\sghome\UserAccountLogs {

    const CHANGE_TYPE_SYSTEM_GRANT = 5;
    const CHANGE_TYPE_SYSTEM_CONSUME = 6;
    const CHANGE_TYPE_CVIEW_GRANT = 13;
    const CHANGE_TYPE_CVIEW_CONSUME = 14;
    const CHANGE_TYPE_TEST_GRANT = 21;
    const CHANGE_TYPE_TEST_CONSUME = 22;
    const CHANGE_TYPE_ACTIVITY_GRANT = 25;
    const CHANGE_TYPE_ACTIVITY_CONSUME = 26;
    //
    const CHANGE_TYPE_SHOP_CONSUME = 34;
    const CHANGE_TYPE_SHOP_REFUND = 37;
    //
    const CHANGE_TYPE_THIRD_GRANT = 41;
    const CHANGE_TYPE_THIRD_CONSUME = 42;

    /**
     * 记录交易订单日志
     * @param string $operation 
     * @param string $explain 
     * @throws Exception
     */
    public function rollback($mark) {
        if (!$mark) {
            $mark = '积分回滚';
        }
        $this->setAttributes([
            'is_rollback' => 2,
            'rollback_remark' => $mark,
            'rollback_user_id' => Yii::$app->user->id,
            'rollback_time' => time(),
        ]);
        if (!$this->save()) {
            throw new Exception('积分回滚失败！');
        }
        $points = $this->change_credit;
        $account = $this->account;
        if (!$account) {
            throw new Exception('积分账户异常！');
        }
        //可用积分
        $account->available_credit -= $points;
        //消费积分
        $account->spend_credit += $points;
        if (!$account->save()) {
            throw new Exception('账户积分回滚失败！');
        }
    }

}
